
/**
 *  私聊socket
 */
const url = "ws://127.0.0.1:8080/renren-fast/app/chat/";
export default {
	websocket: null,
	toId:null,
	async init(toId){
		this.toId = toId
	},
	open() {
		let newUrl = url + uni.getStorageSync('token');
		if ('WebSocket' in window) {
			//连接WebSocket节点
			this.websocket = new WebSocket(newUrl);
		} else {
			alert('Not support websocket')
		}
		//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
		window.onbeforeunload = function() {
			this.websocket.close();
		}
		return this.websocket;
	},
	send(content){
		let message = {
			token:uni.getStorageSync('token'),
			toId:this.toId,
			content
		}
		this.websocket.send(JSON.stringify(message))
	}
}